package crud

import (
	"codeless/dao"
	models "codeless/model"
	"codeless/storage"
	"errors"
	"mime/multipart"
	"time"
)

type FileService struct {
}

func (u *FileService) UploadTime(fh *multipart.FileHeader, fileId, groupId string, currentTime int64) (*models.SysFile, error) {

	fs := storage.GetStorage()
	resp, err := fs.Upload(fh)
	if err != nil {
		return nil, err
	}
	ctime := time.Now().Unix()
	if currentTime != 0 {
		ctime = currentTime
	}
	arg := models.SysFile{
		Id:         fileId,
		GroupId:    groupId,
		AttachName: fh.Filename,
		RealName:   resp.ObjectName,
		RemoteId:   resp.Id,
		RemoteUrl:  resp.Url,
		CreateTime: ctime,
	}
	argMap := Struct2Map(arg)
	sqlExplain, err := LoadAddProcessMap("file.add.add", argMap)
	if err != nil {
		return nil, err
	}
	ret, _ := dao.ExecRawSql(sqlExplain.Sql, sqlExplain.Args)
	if ret == 0 {
		return nil, errors.New("保存附件失败")
	}
	return &arg, nil
}
func (u *FileService) Upload(fh *multipart.FileHeader, fileId, groupId string) (*models.SysFile, error) {
	return u.UploadTime(fh, fileId, groupId, 0)
}

func (u *FileService) Get(id string) models.SysFile {
	sqlExplain, err := LoadAddProcessMap("file.get.get", map[string]interface{}{
		"id": id,
	})
	if err != nil {
		return models.SysFile{}
	}
	var info models.SysFile
	dao.QueryRawSql(sqlExplain.Sql, sqlExplain.Args, &info)
	return info
}
func (u *FileService) Del(id string) (int64, error) {
	sqlExplain, err := LoadAddProcessMap("file.del.del", map[string]interface{}{
		"id": id,
	})
	if err != nil {
		return 0, err
	}
	return dao.ExecRawSql(sqlExplain.Sql, sqlExplain.Args)
}
func (u *FileService) List(groupId string) []models.SysFile {

	sqlExplain, err := LoadAddProcessMap("file.list.list_group", map[string]interface{}{
		"group_id": groupId,
	})
	if err != nil {
		return make([]models.SysFile, 0)
	}
	var list []models.SysFile
	dao.QueryRawSql(sqlExplain.Sql, sqlExplain.Args, &list)
	return list
}
